package com.ls.atf.core.web.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

import com.ls.atf.core.web.elements.Text;
import com.ls.atf.core.web.WebPage;
import com.ls.atf.core.web.elements.Button;
import com.ls.atf.core.web.elements.TextInput;
import com.ls.atf.data.objects.NewUser;

public class CreateUserPage extends WebPage<CreateUserPage> {

	private static final String PAGE_URL = BASE_URL + "/admin_users/new";

	public CreateUserPage(WebDriver driver) {
		super(driver);
	}

	@Override
	public CreateUserPage load() {
		driver.get(PAGE_URL);
		return this;
	}

	@Override
	public boolean isAvailable() {
		return getUsernameInput().isAvailable()
				&& getPasswordInput().isAvailable()
				&& getPasswordConfirmationInput().isAvailable()
				&& getFirstNameInput().isAvailable()
				&& getLastNameInput().isAvailable()
				&& getEmailInput().isAvailable()
				&& getSubmitButton().isAvailable();
	}

	public CreateUserPage fillInForm(String username, String password,
			String passwordConfirmation, String firstName, String lastName,
			String email) {
		getUsernameInput().inputText(username);
		getPasswordInput().inputText(password);
		getPasswordConfirmationInput().inputText(passwordConfirmation);
		getFirstNameInput().inputText(firstName);
		getLastNameInput().inputText(lastName);
		getEmailInput().inputText(email);
		return this;
	}

	public CreateUserPage submitFormExpectingError() {
		getSubmitButton().click();
		return this.waitUntilAvailable();
	}

	public String getPageErrorMessage() {
		return new Text(driver, By.xpath("id('errorExplanation')/ul/li[1]"))
				.getText();
	}

	private TextInput getUsernameInput() {
		return new TextInput(driver, By.id("admin_user_username"));
	}

	private TextInput getPasswordInput() {
		return new TextInput(driver, By.id("admin_user_password"));
	}

	private TextInput getPasswordConfirmationInput() {
		return new TextInput(driver, By.id("admin_user_password_confirmation"));
	}

	private TextInput getFirstNameInput() {
		return new TextInput(driver, By.id("admin_user_first_name"));
	}

	private TextInput getLastNameInput() {
		return new TextInput(driver, By.id("admin_user_last_name"));
	}

	private TextInput getEmailInput() {
		return new TextInput(driver, By.id("admin_user_email"));
	}

	private Button getSubmitButton() {
		return new Button(driver, By.name("commit"));
	}

	public CreateUserPage fillInFormWithUser(NewUser user) {
		return fillInForm(
				user.getUsername(), 
				user.getPassword(),
				user.getPasswordConfirmation(), 
				user.getFirstName(),
				user.getLastName(), 
				user.getEmail()
				);
	}

}
